﻿using SD.Infrastructure.Constants;
using SD.OpcServer.Models.Entities;
using SD.Toolkits.EntityFramework.Extensions;
using System.Data.Entity;

namespace SD.OpcServer.Models.Base
{
    /// <summary>
    /// EF上下文
    /// </summary>
    public class DbSession : DbContext
    {
        /// <summary>
        /// 构造器
        /// </summary>
        public DbSession()
            : base(GlobalSetting.DefaultConnectionString)
        {
            this.Database.CreateIfNotExists();
        }

        /// <summary>
        /// 变量列表
        /// </summary>
        public DbSet<Variable> Variables { get; set; }

        /// <summary>
        /// 变量组列表
        /// </summary>
        public DbSet<VariableHistory> VariableHistories { get; set; }

        /// <summary>
        /// 模型创建事件
        /// </summary>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //设置编号长度
            modelBuilder.Entity<Variable>().Property(variable => variable.Number).HasMaxLength(64);

            //设置唯一键索引
            modelBuilder.Entity<Variable>().HasIndex("IX_Number", IndexType.Unique, table => table.Property(variable => variable.Number));

            base.OnModelCreating(modelBuilder);
        }
    }
}
